import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { applyStep1, applyStep2, applyStep3, success, scrollToTop } from '@/utils/util';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { Breadcrumb, Button, ConfigProvider, Form, Input, InputNumber, message } from 'antd';
import type { MatterVo, PolicyInfoMaterialVo } from '@/services/homePage/homePage';
import { findMatterById, createPolicyInfoApplyMatter } from '@/services/homePage/homePage';
import { history, connect } from 'umi';
import type { Dispatch } from 'umi';
import { getUserInfo, getToken, removeToken } from '@/utils/storage';
import type { UploadChangeParam } from 'antd/lib/upload/interface';
import zhCN from 'antd/lib/locale/zh_CN';

type MaterialVo = {
  applyMatterId: number | undefined;
  fileName: string;
  url: string;
  title: string;
};

type PropsType = {
  dispatch: Dispatch;
};

const OnlineApply: React.FC<PropsType> = (props) => {
  const { dispatch } = props;
  const [step, setStep] = useState<number>(1);
  const [stepImg, setStepImg] = useState<string>(applyStep1);
  const [matter, setMatter] = useState<MatterVo>();
  const [materials, setMaterials] = useState<PolicyInfoMaterialVo[]>([]);
  const [infoValues, setInfoValues] = useState<{}>();
  const [policyInfoApplyMaterialVos, setPolicyInfoApplyMaterialVos] = useState<MaterialVo[]>([]);
  const [form] = Form.useForm();
  const [uploadForm] = Form.useForm();
  const userInfo = getUserInfo();
  useEffect(() => {
    scrollToTop();
    const { id } = props.history.location.query;
    findMatterById({ id }).then((resp) => {
      const { policyInfoDeclareMaterials } = resp.results;
      setMatter(resp.results);
      setMaterials(policyInfoDeclareMaterials);
      form.setFieldsValue({
        applyMatterName: resp.results?.title,
        companyName: userInfo.companyName,
        managerPhone: userInfo.phone,
      });
    });
  }, []);
  useEffect(() => {
    switch (step) {
      case 1:
        setStepImg(applyStep1);
        break;
      case 2:
        setStepImg(applyStep2);
        break;
      case 3:
        setStepImg(applyStep3);
        break;
      default:
        break;
    }
  }, [step]);

  const gotoStep2 = async () => {
    const values = await form.validateFields();
    setStep(2);
    setInfoValues(values);
    scrollToTop();
  };

  const gotoStep3 = async () => {
    const requestParam = {
      ...infoValues,
      policyInfoApplyMaterialVos,
      applyCompanyId: userInfo.userId,
      applyMatterId: matter?.id,
    };
    console.log('requestParam==', requestParam);
    try {
      const createResp = await createPolicyInfoApplyMatter(requestParam);
      if (createResp.errorCode === 0) {
        setStep(3);
        scrollToTop();
      }
    } catch (error) {
      message.error('申请失败，请重试');
    }
  };

  const handleFileChange = (e: UploadChangeParam, material: PolicyInfoMaterialVo) => {
    if (e.file.status === 'done') {
      uploadForm?.setFieldsValue({ [material.id]: e.fileList });
      const materialVo = [];
      if (e.file?.response?.results) {
        materialVo.push({
          applyMatterId: matter?.id,
          fileName: e.file.name,
          url: e.file?.response?.results,
          title: material?.fileName,
        });
        setPolicyInfoApplyMaterialVos(materialVo);
      }
    } else if (e.file.status === 'error') {
      form.setFieldsValue({
        [material.id]: null,
      });
      removeToken();
      dispatch({
        type: 'login/fetchIsLogin',
        payload: false,
      });
      history.push('/');
      message.error('登录过期请重新登录');
    }
  };

  return (
    <>
      <div className={styles.applyHeader}>
        <p className={styles.title}>在线申请</p>
      </div>
      <div className={styles.wrapper}>
        <div className={styles.breadCrumb}>
          <Breadcrumb separator="">
            <Breadcrumb.Item>您的位置</Breadcrumb.Item>
            <Breadcrumb.Separator>:</Breadcrumb.Separator>
            <Breadcrumb.Item href="">首页</Breadcrumb.Item>
            <Breadcrumb.Separator />
            <Breadcrumb.Item href="#/policyList">政策申报</Breadcrumb.Item>
            <Breadcrumb.Separator />
            <Breadcrumb.Item>在线申报</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className={styles.applyForm}>
          <div className={styles.formInner}>
            <img src={stepImg} />
            {step === 1 && (
              <Form layout="vertical" className={styles.form} form={form} onFinish={gotoStep2}>
                <Form.Item
                  name="applyMatterName"
                  label="申请项目名称"
                  rules={[{ required: true, message: '设备属性不能为空' }]}
                >
                  <Input placeholder="请输入项目名称" disabled={true} />
                </Form.Item>
                <Form.Item
                  name="companyName"
                  label="单位名称"
                  rules={[{ required: true, message: '单位名称不能为空' }]}
                >
                  <Input placeholder="请输入项目名称" disabled={true} />
                </Form.Item>
                <Form.Item
                  name="basicAccountBank"
                  label="基本户银行"
                  rules={[{ required: true, message: '基本户银行不能为空' }]}
                >
                  <Input placeholder="请输入基本户银行" />
                </Form.Item>
                <Form.Item
                  name="basicAccount"
                  label="基本户账户"
                  rules={[{ required: true, message: '基本户账户不能为空' }]}
                >
                  <Input placeholder="请输入基本户账户" />
                </Form.Item>
                <Form.Item
                  name="manager"
                  label="经办人"
                  rules={[{ required: true, message: '经办人不能为空' }]}
                >
                  <Input placeholder="请输入经办人" />
                </Form.Item>
                <Form.Item
                  name="managerPhone"
                  label="手机号"
                  rules={[{ required: true, message: '手机号不能为空' }]}
                >
                  <Input placeholder="请输入手机号" disabled={true} />
                </Form.Item>
                <Form.Item
                  name="managerEmail"
                  label="E-mail"
                  rules={[
                    { required: true, message: 'E-mail不能为空' },
                    {
                      pattern:
                        /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
                      message: '邮箱格式错误',
                    },
                  ]}
                >
                  <Input placeholder="请输入您的E-mail" />
                </Form.Item>
                <Form.Item
                  name="managerTel"
                  label="办公电话"
                  rules={[{ required: true, message: '办公电话不能为空' }]}
                >
                  <Input placeholder="请输入办公电话" />
                </Form.Item>
                <Form.Item
                  name="fundingCriteria"
                  label="资助标准"
                  rules={[{ required: true, message: '资助标准不能为空' }]}
                >
                  <Input placeholder="请输入资助标准" />
                </Form.Item>
                <Form.Item
                  name="applyAmount"
                  label="本次申请金额（元）"
                  rules={[{ required: true, message: '本次申请金额不能为空' }]}
                >
                  <InputNumber placeholder="请输入本次申请金额" min={0} />
                </Form.Item>
                <Form.Item name="descriptionRedemptionMatters" label="兑现事项情况说明" rules={[]}>
                  <Input placeholder="请输入事项情况说明" />
                </Form.Item>
                <div className={styles.gotoStep2Btn}>
                  <Button htmlType="submit">下一步</Button>
                </div>
              </Form>
            )}
            {step === 2 && (
              <div className={styles.materialWrapper}>
                <ConfigProvider locale={zhCN}>
                  <Form
                    layout="vertical"
                    className={styles.form}
                    form={uploadForm}
                    onFinish={gotoStep3}
                  >
                    <div className={styles.desc}>申请清单</div>
                    {materials?.map((_material: PolicyInfoMaterialVo) => {
                      return (
                        <div className={styles.materialItem}>
                          <div className={styles.fieldsName}>
                            <div className={styles.fieldsNameLeft} title={_material.fileName}>
                              {_material.fileName}
                            </div>
                          </div>
                          <ProFormUploadButton
                            name={_material.id}
                            fieldProps={{
                              maxCount: 1,
                              name: 'file',
                              headers: {
                                'Access-Token': getToken() || '',
                              },
                              onChange: (e) => handleFileChange(e, _material),
                            }}
                            accept={'.pdf,.doc,.docx,.img,.png'}
                            action={`${WEB_DOMAIN.apiDomain}/files/uploadFile`}
                            rules={[{ required: true, message: '材料清单必传' }]}
                          />
                        </div>
                      );
                    })}
                    <div className={styles.gotoStep2Btn}>
                      <Button htmlType="submit">提交</Button>
                    </div>
                  </Form>
                </ConfigProvider>
              </div>
            )}

            {step === 3 && (
              <div className={styles.successWrapper}>
                <img src={success} />
                <div className={styles.successText}>在线申请提交成功</div>
                <div className={styles.gotoStep2Btn}>
                  <Button onClick={() => history.push('/personalCenter')}>前往查看</Button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default connect()(OnlineApply);
